import React, { useEffect, useState } from "react"
import { Canvas, View } from "@tarojs/components"
import uCharts from '@qiun/ucharts';
import Taro from "@tarojs/taro";
import moment from "moment";
import categorys from "@/store/categorys";
import { MoneyFormat } from "@/utils/format";
import viewMode from "@/store/viewMode";
import "./index.scss"

interface dataType {
    balance: number
    category: number
    date: string | null
    expense: number
    income: number
    month: string | null
    userId: number
}

let uChartsInstance: any = {};
const PieChart: React.FC<{
    month?: string,
    onSelect: (val: dataType | undefined, moneyType: string) => void,
    pieData: dataType[],
    hide: boolean
}> = ({ month, onSelect, pieData, hide }) => {

    const [moneyType, setMoneyType] = useState('expense')

    const dataHandler = (moneyType) => {
        return pieData.map(item => {
            return {
                value: item[moneyType],
                name: categorys.categoryMap[item.category]?.name,
                category: item.category
            }
        }).filter(item => {
            return item.value > 0
        })
    }

    useEffect(() => {
        if (pieData?.length) {
            drawCharts(moneyType)
        }
    }, [pieData, moneyType])

    const drawCharts = (moneyType) => {
        const sysInfo = Taro.getWindowInfo();
        let ctx = Taro.createCanvasContext('pie_id');
        uChartsInstance = new uCharts({
            type: "pie",
            context: ctx,
            width: 700 / 750 * sysInfo.screenWidth,
            height: 500 / 750 * sysInfo.screenWidth,
            fontColor: viewMode.isNight ? '#fff' : '#25283b',
            series: [
                {
                    data: dataHandler(moneyType)
                }
            ],
            pixelRatio: 1,
            animation: true,
            background: "#FFFFFF",
            color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4", "#ea7ccc"],
            padding: [5, 5, 5, 5],
            enableScroll: false,
            legend: {
                fontColor: viewMode.isNight ? '#fff' : '#25283b',
                fontSize: 12
            },
            extra: {
                tooltip: {},
                pie: {
                    activeOpacity: 0.5,
                    activeRadius: 10,
                    offsetAngle: 0,
                    labelWidth: 15,
                    border: true,
                    borderWidth: 2,
                    borderColor: "#FFFFFF"
                }
            }
        });
    }

    const switchMoneyType = () => {
        const type = moneyType === 'income' ? 'expense' : 'income'
        setMoneyType(type)
        onSelect(undefined, type)
    }

    const tap = (e) => {
        uChartsInstance.touchLegend(e);
        uChartsInstance.showToolTip(e, {
            // formatter: (item, category, index, opts) => {
            formatter: (item) => {
                const categoryData = pieData.find(pie => pie.category === item.category)
                onSelect(categoryData, moneyType)
                return `${item.name}：${MoneyFormat(item.value)}`;
            }
        });
    }

    return (<View className="month-chart-container card-background flex-column">
        <View className="type-switch font-size28 flex-row flex-item text-main-color">
            <View onClick={switchMoneyType} className={`type-item ${moneyType === 'expense' ? 'active' : ''}`}>
                <View className="type-name">支出</View>
                <View className="bottom-line bg-contrast-color"></View>
            </View>
            <View onClick={switchMoneyType} className={`type-item ${moneyType === 'income' ? 'active' : ''}`}>
                <View className="type-name">收入</View>
                <View className="bottom-line bg-contrast-color"></View>
            </View>
            <View className="flex1"></View>
            <View className="chart-title right-content">{moment(month).format('YYYY年MM月')}</View>
        </View>
        <Canvas
            canvas-id="pie_id"
            id="pie_id"
            className={`pie-chart + ${hide ? 'hide' : ''}`}
            onTouchEnd={tap} />
        <View className="tips font-size20 text-main-color">注：点击分类，展示相应的账单</View>
    </View>)
}

export default PieChart